#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <mutex>
#include "util.hpp"
#include "log.hpp"

namespace ns_index
{
    //正排索引的Value字段
    struct DocInfo
    {
        std::string title;
        std::string content;
        std::string url;
        uint64_t doc_id; //文档的ID值
    };
    //倒排索引的Value字段的其中之一
    struct InvertedElem
    {
        uint64_t doc_id;
        std::string word; //关键字
        int weight; //权重
    };

    typedef std::vector<InvertedElem> InvertedList;
    class Index
    {
    private:
        std::vector<DocInfo> _forward_index; //正排索引
        std::unordered_map<std::string, InvertedList> _inverted_index; //倒排索引 
    public:
        ~Index(){};

        // 根据文档ID值（doc_id），在正排索引中找到对应的文档内容
        DocInfo *GetForwardIndex(uint64_t doc_id)
        {
            if (doc_id >= _forward_index.size())
            {
                LOG(WARNING, std::to_string((int)doc_id)+"doc_id out range error!");
                return nullptr;
            }
            return &_forward_index[doc_id];
        }
        // 根据关键字（word），获得倒排拉链
        InvertedList *GetInvertList(const std::string &word)
        {
            auto iter = _inverted_index.find(word);
            if (iter == _inverted_index.end())
            {
                LOG(WARNING, word+" have no InvertedList!");
                return nullptr;
            }
            return &(iter->second);
        }
        // 构建正排索引和倒排索引
        bool BuildIndex(const std::string &raw_path)
        {
            std::ifstream in(raw_path, std::ios::in | std::ios::binary); // 打开raw.txt文件
            if (!in.is_open())
            {
                std::cerr << "sorry " << raw_path << " open error!" << std::endl;
                return false;
            }
            std::string line_file;
            int count = 0;
            while (std::getline(in, line_file))
            {
                DocInfo *doc = BulidForwardIndex(line_file); // 构建正排索引
                if (doc == nullptr)
                {
                    std::cerr << "build: " << line_file << "errro" << std::endl;
                    continue;
                }
                BulidInvertedIndex(*doc); // 构建倒排索引
                count++;
                if(count % 50 == 0)
                    LOG(NORMAL, "The number of documents that have completed indexing: "+std::to_string(count));
            }
            return true;
        }

    private:
        // 支持正排索引构建的函数
        DocInfo *BulidForwardIndex(const std::string &line_file)
        {
            // 1.解析line_file，将字符串切分成3个string字段
            std::vector<std::string> results;
            const std::string SEP = "\3";
            ns_util::StringUtil::CutString(line_file, &results, SEP);
            if (results.size() != 3)
                return nullptr;
            // 2. 填充DcoInfo字段
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = _forward_index.size();
            // 3. 插入到正排索引的vector中
            _forward_index.push_back(std::move(doc));

            return &_forward_index.back();
        }
        // 支持倒排索引构建的函数
        void BulidInvertedIndex(const DocInfo &doc)
        {
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt() : title_cnt(0), content_cnt(0) {}
            };

            std::unordered_map<std::string, word_cnt> word_map; // 用来暂存词频的映射表
            // 对标题进行分词
            std::vector<std::string> title_words;
            ns_util::JiebaUtil::CutString(doc.title, &title_words);
            // 对标题进行词频统计
            for (std::string &s : title_words)
            {
                boost::to_lower(s);
                word_map[s].title_cnt++;
            }
            // 对内容进行分词
            std::vector<std::string> content_words;
            ns_util::JiebaUtil::CutString(doc.content, &content_words);
            // 对内容进行词频统计
            for (std::string &s : content_words)
            {
                boost::to_lower(s);
                word_map[s].content_cnt++;
            }
#define X 10
#define Y 1
            // 构建倒排索引
            for (auto &word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id; // 这也就是为什么在DocInfo中也添加一个doc_id字段
                item.word = word_pair.first;
                //因为content中的内容，包含了title去标签之后的内容，相当于重复计算了
                if(word_pair.second.title_cnt > 0) word_pair.second.content_cnt -= word_pair.second.title_cnt;
                item.weight = (word_pair.second.title_cnt * X) + (word_pair.second.content_cnt * Y);

                InvertedList &inverted_list = _inverted_index[word_pair.first];
                inverted_list.push_back(item);
            }
        }
    public:
        static Index* GetInstance()
        {
            if(nullptr == instance)
            {
                mtx.lock();
                if(nullptr == instance)
                    instance = new Index();
                mtx.unlock();
            }
            return instance;
        }
    private:
        Index(){};
        Index(const Index&) = delete;
        Index& operator=(const Index&) = delete;

        static Index* instance;
        static std::mutex mtx;
    };
    Index* Index::instance = nullptr;
    std::mutex Index::mtx;
}